package com.syj.jsxjj.ui.renzheng.activity;

import android.Manifest;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.google.gson.Gson;
import com.syj.jsxjj.R;
import com.syj.jsxjj.app.App;
import com.syj.jsxjj.base.BaseActivity;
import com.syj.jsxjj.base.PermissionsListener;
import com.syj.jsxjj.http.HttpManager;
import com.syj.jsxjj.http.HttpSubscriber;
import com.syj.jsxjj.ui.authentication.bean.MyRelationBean;
import com.syj.jsxjj.ui.authentication.bean.RelationBean;
import com.syj.jsxjj.ui.renzheng.bean.ContactBean;
import com.syj.jsxjj.ui.renzheng.bean.ContentBean;
import com.syj.jsxjj.ui.renzheng.fragment.AuthenFragment;
import com.syj.jsxjj.util.StringUtil;
import com.syj.jsxjj.util.ToastUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/*
 * 紧急联系人
 * xiejingwen
 */
public class AuthEmergencyLinkManActivity extends BaseActivity {


    @BindView(R.id.tv_relation)
    TextView mTvRelation;
    @BindView(R.id.tv_contact_name)
    TextView mTvContactName;
    @BindView(R.id.tv_relation2)
    TextView mTvRelation2;
    @BindView(R.id.tv_contact_name2)
    TextView mTvContactName2;

    private ContentBean contentBean;
    /*********
     * 获取关系列表
     */
    private MyRelationBean bean = null;
    private List<RelationBean> relations = null;
    private List<RelationBean> relations2 = null;
    private int CODE_GET_CONTACT = 110;
    private int CODE_GET_CONTACT2 = 111;

    private String message = "紧急联系人手机号码有误，请重新选择";
    private String select_contact_name = "";
    private String select_contact_phone = "";
    private String select_contact_name2 = "";
    private String select_contact_phone2 = "";

    /********
     * 选择与本人的关系
     */
    private int curPos = 0;
    private int curPos2 = 0;
    private OptionsPickerView pv;
    private ArrayList<String> professionalList = new ArrayList<>();

    @Override
    public int getLayoutId() {
        return R.layout.activity_auth_contact;
    }

    @Override
    public void initPresenter() {
    }

    @Override
    public void loadData() {
        mTitle.setTitle("紧急联系人");
        contentBean = getIntent().getParcelableExtra(AuthenFragment.CONTENT_BEAN);
        if (contentBean==null){
            contentBean = new ContentBean();
        }
        if (contentBean.getContract()!=null){
            mTvRelation.setText(contentBean.getContract().getRelation());
            mTvContactName.setText(contentBean.getContract().getName());
            select_contact_name = contentBean.getContract().getName();
            select_contact_phone = contentBean.getContract().getPhone();
        }
        initLisenters();
    }


    private void initLisenters() {
        mTvContactName.addTextChangedListener(changeText);
        mTvContactName2.addTextChangedListener(changeText);
        mTvRelation.addTextChangedListener(changeText);
        mTvRelation2.addTextChangedListener(changeText);
    }

    TextWatcher changeText = new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            showSaveBtn();
        }
    };

    @Override
    protected void onActivityResult(int arg0, int arg1, Intent arg2) {
        if (arg0 == CODE_GET_CONTACT || arg0 == CODE_GET_CONTACT2) {
            if (arg1 == RESULT_OK) {
                Uri contactData = arg2.getData();
                Cursor cursor = null;
                try {
                    cursor = getContentResolver().query(contactData, null, null, null, null);
                    if (cursor != null && cursor.moveToFirst()) {
                        getContactPhoneInfo(cursor, arg0);
                        if (!cursor.isClosed()) {
                            cursor.close();
                        }
                    } else {
                        toAppSettings("通讯录权限已被禁止", false);
                    }
                } catch (SecurityException e) {
                    ToastUtil.showToast("无法获取系统通讯录");
                }
            }
        }
        super.onActivityResult(arg0, arg1, arg2);
    }


    private void getContactPhoneInfo(Cursor cursor, int code) {
        int phoneColumn = cursor
                .getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER);
        int phoneNum = cursor.getInt(phoneColumn);

        if (phoneNum > 0) {
            // 获得联系人的ID号  
            int idColumn = cursor.getColumnIndex(ContactsContract.Contacts._ID);
            String contactId = cursor.getString(idColumn);
            // 获得联系人电话的cursor  
            Cursor phone = getContentResolver().query(
                    ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                    null,
                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "="
                            + contactId, null, null);
            if (phone == null) {
                ToastUtil.showToast("通讯录获取失败");
                return;
            }
            if (phone.moveToFirst()) {
                //为了防止用户关闭联系人权限，所以在选择到联系人时就开始上传联系人
                for (; !phone.isAfterLast(); phone.moveToNext()) {
                    int index = phone
                            .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
                    int typeindex = phone
                            .getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE);
                    // 取得联系人名字   
                    int nameFieldColumnIndex = cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME);
                    if (TextUtils.isEmpty(phone.getString(index))) {
                        ToastUtil.showToast("联系人手机号为空，请重新选择");
                        if (code == CODE_GET_CONTACT) {
                            select_contact_name = "";
                            select_contact_phone = "";
                            mTvContactName.setText(select_contact_name);
                        } else if (code == CODE_GET_CONTACT2) {
                            select_contact_name2 = "";
                            select_contact_phone2 = "";
                            mTvContactName2.setText(select_contact_name2);
                        }
                        if (!phone.isClosed()) {
                            phone.close();
                        }
                        return;
                    } else {
                        String mPhone = StringUtil.toNum(phone.getString(index));
                        if (mPhone.length() < 11) {
                            ToastUtil.showToast(message);
                            return;
                        } else if (mPhone.length() > 11) {
                            if (!mPhone.startsWith("86")) {
                                ToastUtil.showToast(message);
                                return;
                            } else {
                                mPhone = mPhone.substring(2, mPhone.length());
                                if (mPhone.length() != 11) {
                                    ToastUtil.showToast(message);
                                    return;
                                }
                            }
                        } else {
                            if (!mPhone.startsWith("1")) {
                                ToastUtil.showToast(message);
                                return;
                            }
                        }
                        if (code == CODE_GET_CONTACT) {
                            select_contact_name = cursor.getString(nameFieldColumnIndex);
                            select_contact_phone = mPhone;
                            mTvContactName.setText(select_contact_name);
                        } else if (code == CODE_GET_CONTACT2) {
                            select_contact_name2 = cursor.getString(nameFieldColumnIndex);
                            select_contact_phone2 = mPhone;
                            mTvContactName2.setText(select_contact_name2);
                        }
                    }
                }
                if (!phone.isClosed()) {
                    phone.close();
                }
            } else {
                ToastUtil.showToast(message);
            }
        } else {
            ToastUtil.showToast(message);
        }

    }


    @OnClick({R.id.rl_relation, R.id.rl_getcontact, R.id.rl_relation2, R.id.rl_getcontact2})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rl_relation:
                if (pv == null) {
                    professionalList.add("父母");
                    professionalList.add("子女");
                    professionalList.add("兄妹");
                    professionalList.add("配偶");
                    pv = new OptionsPickerView(mContext);
                    pv.setPicker(professionalList);
                    pv.setCyclic(false);
                    pv.setOnoptionsSelectListener(new OptionsPickerView.OnOptionsSelectListener() {
                        @Override
                        public void onOptionsSelect(int options1, int option2, int options3) {
                            mTvRelation.setText(professionalList.get(options1));
                        }
                    });
                }
                pv.show();
                break;
            case R.id.rl_getcontact:
                getSelfContact(CODE_GET_CONTACT);
                break;
            case R.id.rl_relation2:
                break;
            case R.id.rl_getcontact2:
                getSelfContact(CODE_GET_CONTACT2);
                break;
        }
    }

    /**
     * 显示保存按钮
     */
    private void showSaveBtn() {
        mTitle.setRightTitle("保存", new OnClickListener() {
            @Override
            public void onClick(View v) {
                saveEmergeencyContact();
            }
        });
    }

    /*********
     * 保存联系人信息
     */
    private void saveEmergeencyContact() {
        if (StringUtil.isBlank(select_contact_name) || StringUtil.isBlank(select_contact_phone)) {
            ToastUtil.showToast("请选择直系亲属紧急联系人");
            return;
        }
        if (StringUtil.isBlankEdit(mTvRelation)) {
            ToastUtil.showToast("请选择直系亲属紧急联系人关系");
            return;
        }
        /*if (StringUtil.isBlank(select_contact_name2) || StringUtil.isBlank(select_contact_phone2)) {
            ToastUtil.showToast("请选择其他联系人");
            return;
        }
        if (StringUtil.isBlankEdit(mTvRelation2)) {
            ToastUtil.showToast("请选择其他联系人关系");
            return;
        }
        if (relations == null || relations2 == null) {
            ToastUtil.showToast("加载数据异常,请稍后再试");
            return;
        }*/
        ContactBean contactBean = new ContactBean();
        contactBean.setName(select_contact_name);
        contactBean.setPhone(select_contact_phone);
        contactBean.setRelation(mTvRelation.getText().toString());
        contentBean.setContract(contactBean);
        Log.e("contentBean=",new Gson().toJson(contentBean));
        toSubscribe(HttpManager.getApi().saveCertification("1", new Gson().toJson(contentBean)), new HttpSubscriber() {
            @Override
            protected void _onStart() {
                App.loadingDefault(mActivity);
            }

            @Override
            protected void _onNext(Object o) {
                ToastUtil.showToast("保存成功");
                finish();
            }

            @Override
            protected void _onError(String message) {
                ToastUtil.showToast(message);
            }

            @Override
            protected void _onCompleted() {
                App.hideLoading();
            }
        });
    }


    /**
     * 跳转系统联系人列表
     *
     * @param code
     */
    private void getSelfContact(final int code) {
        requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, new PermissionsListener() {
            @Override
            public void onGranted() {
                Intent intent = new Intent(Intent.ACTION_PICK,
                        ContactsContract.Contacts.CONTENT_URI);
                startActivityForResult(intent, code);
            }

            @Override
            public void onDenied(List<String> deniedPermissions, boolean isNeverAsk) {
                if (isNeverAsk) {
                    toAppSettings("通讯录权限已被禁止", false);
                }
            }
        });
    }

}
